<script setup>
  import { ref } from 'vue'
  import { loginApi } from '@/apis/user.js'
  import { useUserStore } from '@/stores/user.js'
  import { onLoad } from '@dcloudio/uni-app'

  const store = useUserStore()

  // 0. 接收传递的参数
  const redirectURL = ref('')
  const routerType = ref('')
  onLoad((options) => {
    redirectURL.value = options.redirectURL
    routerType.value = options.routerType
  })

  // 1. 定义数据
  const formData = ref({
    account: 'yejh666',
    password: '123456',
  })

  // 2. 校验规则对象
  const accountRules = {
    account: {
      rules: [
        { required: true, errorMessage: '请输入登录账号' },
        { pattern: /^[a-zA-Z0-9]{6,8}$/, errorMessage: '登录账号格式不正确' },
      ],
    },
    password: {
      rules: [
        { required: true, errorMessage: '请输入登录密码' },
        { pattern: /^\d{6}$/, errorMessage: '登录密码格式不正确' },
      ],
    },
  }

  // 3. 提交表单
  const accountForm = ref()
  const onSubmitForm = async () => {
    try {
      // 3.1 调用登录接口
      const formData = await accountForm.value.validate()
      const res = await loginApi(formData)
      // 3.2 把token存储到pinia
      store.setToken(res.data)
      // 3.3 登录成功后跳转
      uni[routerType.value]({
        url: redirectURL.value,
      })
    } catch (e) {
      console.error(e)
    }
  }
</script>

<template>
  <uni-forms
    class="login-form"
    ref="accountForm"
    :model="formData"
    :rules="accountRules"
  >
    <uni-forms-item name="account">
      <input
        v-model="formData.account"
        type="text"
        placeholder="请输入账号"
        class="uni-input-input"
        placeholder-style="color: #818181"
      />
    </uni-forms-item>
    <uni-forms-item name="password">
      <input
        v-model="formData.password"
        type="password"
        placeholder="请输入密码"
        class="uni-input-input"
        placeholder-style="color: #818181"
      />
    </uni-forms-item>
    <button class="submit-button" @click="onSubmitForm">登录</button>
  </uni-forms>
</template>

<style lang="scss" scoped>
  @import './styles.scss';
</style>
